
/**
*┌──────────────────────────────────────────────────────────────┐
*│　描    述：返佣提现记录                                                    
*│　作    者：gaotang                                            
*│　版    本：1.0    模板代码自动生成                                                
*│　创建时间：2019-02-15 13:42:39                             
*└──────────────────────────────────────────────────────────────┘
*┌──────────────────────────────────────────────────────────────┐
*│　命名空间： BestTrader.Cms.Services                                  
*│　类    名： RebateExtractService                                    
*└──────────────────────────────────────────────────────────────┘
*/
using AutoMapper;
using BestTrader.Cms.Core.Extensions;
using BestTrader.Cms.IRepository;
using BestTrader.Cms.IServices;
using BestTrader.Cms.Models;
using BestTrader.Cms.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;

namespace BestTrader.Cms.Services
{
    public class RebateExtractService: IRebateExtractService
    {
        private readonly IRebateExtractRepository _repository;
        private readonly IManagerRepository _managerRepository;
        private readonly IMapper _mapper;

        public RebateExtractService(IRebateExtractRepository repository, IManagerRepository managerRepository, IMapper mapper)
        {
            _repository = repository;
            _managerRepository = managerRepository;
            _mapper = mapper;
        }
        
        public TableDataModel LoadData(RebateExtractRequestModel model, string UserId, string RoleId)
        {
            string conditions = "where IsDelete=0 and ExtractRMBType = 0 ";// 未删除的所有提现申请记录
            string Key = "";
            if (!model.Key.IsNullOrWhiteSpace())
            {
                conditions += $" and ( ManagerRealName like @Key or ManagerName like @Key )";
                Key = model.Key.ToSqlLikeParam();
            }
            if (!model.State.IsNullOrWhiteSpace())
            {
                //状态 0:待审核,1：提现成功,2：提现取消,3：提现失败
                conditions += $" and State = {model.State}  ";
            }
            if (model.Start.HasValue)
            {
                conditions += $" and ApplyTime >= '{model.Start.Value}' ";
            }
            if (model.End.HasValue)
            {
                conditions += $" and ApplyTime <= '{model.End.Value}' ";
            }
            if (RoleId !="3" ) {
                conditions += $" And ManagerId ={UserId}";
            }
            var list = _repository.GetListPaged(model.Page, model.Limit, conditions, "Id desc",new { Key=Key}).ToList();
            var viewList = new List<RebateExtractListModel>();
            list.ForEach(x => {
                var item = _mapper.Map<RebateExtractListModel>(x);
                item.ExtractRMBMoney = Math.Abs(item.ExtractRMBMoney ?? 0);
                //if (x.ProjectManagerId.HasValue)
                //    item.ProjectManagerName = _managerRepository.GetNameById(x.ProjectManagerId.Value);
                viewList.Add(item);
            });
            return new TableDataModel
            {
                count = _repository.RecordCount(conditions,new { Key = Key }),
                data = viewList,
            };
        }
        /// <summary>
        /// 添加或者修改
        /// </summary>
        /// <param name="item"></param>
        /// <param name="UserId"></param>
        /// <returns></returns>
        public BaseResult AddOrModify(RebateExtractAddOrModifyModel item, string UserId)
        {
            var result = new BaseResult();
            RebateExtract entity;
            var userId = UserId.ToInt32() ?? 0;
            var now = DateTime.Now;
            if (item.Id == 0)
            {
                entity = _mapper.Map<RebateExtract>(item);
                entity.ExtractRMBMoney = -entity.ExtractRMBMoney;
                entity.ExtractRMBType = false;
                entity.State = 0;
                entity.ApplyTime = now;
                entity.AddManagerId = userId;
                
                entity.IsDelete = false;
                entity.AddTime = now;
                var manager = _managerRepository.Get(userId);
                if (manager != null)
                {
                    entity.ManagerId = manager.Id;
                    entity.ManagerName = manager.UserName;
                    entity.ManagerRealName = manager.RealName;
                    entity.RoleId = manager.RoleId;
                }

                if (_repository.Insert(entity) > 0)
                {
                    result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
                }
                else
                {
                    result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                }
            }
            else
            {
                //TODO Modify
                entity = _repository.Get(item.Id);
                if (entity != null)
                {
                    // 取消审核功能状态
                    entity.State = item.State;
                    entity.ModifyManagerId = userId;
                    entity.ModifyTime = now;
                    if (_repository.Update(entity) > 0)
                    {
                        result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                        result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
                    }
                    else
                    {
                        result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                        result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                    }
                }
                else
                {
                    result.ResultCode = ResultCodeAddMsgKeys.CommonFailNoDataCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.CommonFailNoDataMsg;
                }
            }
            return result;
        }

        public decimal GetTotalMoneyByManagerId(string userId)
        {
            decimal result = 0;
            // 获取所有相关的入金和提现金额（未审核和审核通过的记录）
            var list = _repository.GetList($"where ManagerId = {userId} and State in (0,1) ");
            if (list != null && list.Any())
            {
                result = list.Sum(p => p.ExtractRMBMoney) ?? 0;
            }
            return result;
        }

        /// <summary>
        /// 获取营业部成本计算规则
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <returns></returns>
        public decimal GetTotalCostByManagerId(string userId, DateTime startDate, DateTime endDate,bool IsAdmin)
        {
            decimal result = 0;
            //result = _repository.GetTotalCostNewFun(userId, startDate, endDate, IsAdmin);
            result = _repository.GetTotalCostByManagerId(userId, startDate, endDate, IsAdmin);

            return result;
        }


    }
}